import os
import sys
import sqlite3
from PyQt5.QtCore import Qt
from PyQt5 import QtWidgets
from PyQt5.QtWidgets import QMessageBox
from PyQt5.Qt import QDialog, QIcon, QPixmap, QShortcut

from .BaseWindow import BaseWindow
from .._config import UI_RES_PATH


class UiLogin(QDialog, BaseWindow):
    def __init__(self, ipc_keys, db):
        super(UiLogin, self).__init__()

        self.setFixedSize(320, 380)
        self.setWindowTitle('登录')
        self.setWindowIcon(QIcon(str(UI_RES_PATH / 'logo.png')))

        self.ipc_dict = ipc_keys
        self.db_path = db
        self.usermap = {
            '管理员': 'admin',
            '操作员': 'worker'
        }
        self.flag = False

        self.initUI()
        self.connect()

    def initUI(self):
        self.grid_main = QtWidgets.QGridLayout(self)

        self.logo = QtWidgets.QLabel(self)
        self.logo.setPixmap(QPixmap(str(UI_RES_PATH / 'logo.png')))
        self.logo.setAlignment(Qt.AlignCenter)
        self.grid_main.addWidget(self.logo)

        self.tab = QtWidgets.QTabWidget(self)
        for var, txt in [
            ('login_page', '登录'),
            ('change_page', '修改密码'),
        ]:
            setattr(self, var, QtWidgets.QWidget(self))
            page_obj: QtWidgets.QWidget = getattr(self, var)
            setattr(self, 'grid_%s' % var, QtWidgets.QGridLayout(page_obj))
            self.tab.addTab(page_obj, txt)

        self.QDuet(self.login_page, self.grid_login_page, (QtWidgets.QLabel, QtWidgets.QComboBox),
                   'user', text='', items=self.usermap.keys())
        self.label_user.setPixmap(QPixmap(str(UI_RES_PATH / 'user.png')))
        self.USER: QtWidgets.QComboBox
        self.USER.setFixedSize(200, 35)
        self.USER.setStyleSheet("""
                QComboBox{
                  color:#666666;
                  font-size:20x;
                  border:1px solid rgb(190,190,190);
                  border-radius:5px 5px 0px 0px;
                } 
                QComboBox::drop-down {
                      subcontrol-origin: padding;
                      subcontrol-position: top right;
                      width: 20px;
                      
                }
                
                """)
        self.QDuet(self.login_page, self.grid_login_page, (QtWidgets.QLabel, QtWidgets.QLineEdit),
                   'pwd', text='', placeholder='请输入密码')
        self.label_pwd.setPixmap(QPixmap(str(UI_RES_PATH / 'pwd.png')))
        self.PWD: QtWidgets.QLineEdit
        self.PWD.setFixedSize(200, 35)
        self.PWD.setEchoMode(QtWidgets.QLineEdit.Password)
        self.PWD.setStyleSheet("""
                        QLineEdit{
                          color:#666666;
                          font-size:20x;
                          border:1px solid rgb(190,190,190);
                          border-radius:5px 5px 0px 0px;
                        }""")

        self.BTN_LOGIN = QtWidgets.QPushButton('登录', self.login_page)
        self.BTN_LOGIN.setFixedHeight(35)
        self.grid_login_page.addWidget(self.BTN_LOGIN)

        for var, text in [
            ('OLD_PWD', '旧密码'),
            ('NEW_PWD', '新密码'),
            ('VERIFY_PWD', '确认密码'),
        ]:
            _, edit_obj, _ = self.QDuet(self.change_page, self.grid_change_page, (QtWidgets.QLabel, QtWidgets.QLineEdit), var, text=text)
            edit_obj.setEchoMode(edit_obj.Password)
            edit_obj.setFixedSize(180, 30)
        self.BTN_CHANGE = QtWidgets.QPushButton('完成', self.login_page)
        self.BTN_CHANGE.setFixedHeight(35)
        self.grid_change_page.addWidget(self.BTN_CHANGE)

        self.grid_main.addWidget(self.tab)

    def connect(self):
        self.BTN_LOGIN.clicked.connect(self.verify)
        self.BTN_CHANGE.clicked.connect(self.change_pwd)
        self.USER.currentTextChanged[str].connect(self.change_pwd_box_status)
        QShortcut('Esc', self).activated.connect(self.close)
        QShortcut('Enter', self).activated.connect(self.verify)

    def showEvent(self, event):
        if os.path.exists(self.db_path):
            self.conn = sqlite3.connect(str(self.db_path))
            self.cursor = self.conn.cursor()

    def closeEvent(self, event):
        if os.path.exists(self.db_path):
            self.conn.close()
        if not self.flag:
            sys.exit()

    def verify(self):
        user = self.usermap[self.USER.currentText()]
        pwd = self.PWD.text()
        try: db_pwd = self.conn.execute('SELECT PWD FROM AUTHS WHERE USER=?', (user, )).fetchone()[0]
        except: db_pwd = None
        if pwd == db_pwd:
            self.ipc_dict['username'] = user
            self.flag = True
            self.close()
        elif pwd == '':
            QMessageBox.warning(self, '提示', '账户或密码不能为空！', QMessageBox.Yes)
        else:
            QMessageBox.critical(self, '提示', '账户或密码错误！', QMessageBox.Yes)

    def change_pwd_box_status(self, user):
        user = self.usermap[user]
        if user == 'worker':
            self.PWD.clear()
            self.PWD.setEnabled(False)
            self.PWD.setPlaceholderText('无需密码 请直接登录')
        elif user == 'admin':
            self.PWD.setEnabled(True)
            self.PWD.setPlaceholderText('请输入密码')

    def change_pwd(self):
        old_pwd = self.OLD_PWD.text()
        new_pwd = self.NEW_PWD.text()
        verify_pwd = self.VERIFY_PWD.text()
        try: db_pwd = self.conn.execute('SELECT PWD FROM AUTHS WHERE USER=?', ('admin', )).fetchone()[0]
        except: db_pwd = None
        if old_pwd != db_pwd:
            QMessageBox.critical(self, '提示', '旧密码不正确！', QMessageBox.Yes)
            return
        elif len(new_pwd) < 6:
            QMessageBox.warning(self, '提示', '密码不能少于6个字符！', QMessageBox.Yes)
            return
        elif new_pwd != verify_pwd:
            QMessageBox.warning(self, '提示', '两次输入的密码不相同！', QMessageBox.Yes)
            return
        else:
            try:
                self.conn.execute('UPDATE AUTHS SET PWD=? WHERE USER=?', (new_pwd, 'admin'))
                QMessageBox.information(self, '提示', '密码修改成功～', QMessageBox.Yes)
            except:
                QMessageBox.warning(self, '提示', '密码修改失败！', QMessageBox.Yes)



if __name__ == '__main__':
    from PyQt5.Qt import QApplication

    app = QApplication(sys.argv)

    win = UiLogin()
    win.show()

    sys.exit(app.exec_())

